<?php

_include(_OTEKOO_API_."APIDefault");
_include(_OTEKOO_MODEL_."User");
_include(_OTEKOO_MODEL_."UserMapper");

class APIUser extends APIDefault
{
	private $_userMapper = NULL;
	
	public function __construct(APIBootstrap $api){
		parent::__construct($api);
		$this->_userMapper = new UserMapper($this->_api->_db, $this->_api->_scripts);
	}
	
	private function getUser(&$errors)
	{
		$user = new User();
		$user->email = $this->email($errors);		
		$user->full_name = $this->full_name($errors);	
		$user->password = $this->password($errors);	
		$user->token = $this->_request->token;
		return $user;
	}
	
	private function formatUser(&$user)
	{
		unset($user->id);
		unset($user->password);
		return $user;
	}
	
	/** 
	* Default method
	* @http_method post get put
	*/
	public function _default()
	{
		
	}
	
	/** 
	* Create a new user
	* @http_method post get put
	*/
	public function create()
	{
		$code = 202;
		$errors = array();
		try{
			$user = $this->getUser($errors);
			if(empty($errors))
			{
				$this->_userMapper->save($user);
				$user = $this->_userMapper->connect($user);
				$this->formatUser($user);
				$this->_response->user = $user->getData();
			}
		}catch(Exception $e)
		{
			$errors[] = $e->getMessage();
		}
		if(!empty($errors))
		{
			$code = 400;
			$this->_response->errors = $errors;
		}
		$this->response($code);
	}
	
	/** 
	* Identify an user
	* @http_method post get put
	*/
	public function connect()
	{
		$code = 202;
		$errors = array();
		try{
			$user = $this->getUser($errors);
			if(empty($errors))
			{
				$user = $this->_userMapper->connect($user);
				if($user === NULL)
					$errors[] = "The email and password doesn't match.";
				else
					$this->_response->current_user = $this->formatUser($user)->getData();
			}
		}catch(Exception $e)
		{
			$errors[] = $e->getMessage();
		}
		if(!empty($errors))
		{
			$code = 400;
			$this->_response->errors = $errors;
		}
		$this->response($code);
	}
	
	
	/** 
	* Update an user settings
	* @http_method post get put
	*/
	public function update()
	{
		$code = 202;
		$errors = array();
		try{
			$user = $this->getUser($errors);
			if(empty($errors))
			{
				$user = $this->_userMapper->update($user);
				if($user == null)
					$errors[] = "Unknow User";
				else
					$this->_response->current_user = $this->formatUser($user)->getData();
			}
		}catch(Exception $e)
		{
			$errors[] = $e->getMessage();
		}
		if(!empty($errors))
		{
			$code = 400;
			$this->_response->errors = $errors;
		}
		$this->response($code);
	}
}	